﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;
using Microsoft.Xna.Framework.Graphics;
using System.Xml;


namespace Jemgine.EffectEditor
{
	public class EditorState
	{
		public ServiceContainer Services = new ServiceContainer();
        public Jemgine.Engine.EpisodeContentManager Content;
        public Config _config;
        public bool _hasUnsavedChanges = false;

        public Particles.ParticleEffect Effect = null;

        public Action InitializeEffect;
        public Action EffectLoaded;
        public Action UpdateStatus;

        public Func<float> GetZoomFactor;

        private static String PrepareConfigFile()
        {
            System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                + "\\Jemgine\\Editor");
            String ConfigFilename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
                            + "\\Jemgine\\Editor\\effect_ed_config.txt";
            return ConfigFilename;
        }

        public EditorState()
        {
            try
            {
                String ConfigFilename = PrepareConfigFile();
                XmlReader Reader = XmlReader.Create(ConfigFilename);
                _config = IntermediateSerializer.Deserialize<Config>(Reader, ConfigFilename);
                Reader.Close();
            }
            catch (Exception e)
            {
                _config = new Config();
            }

            _config._loadedAssemblies.Add(
                System.Reflection.Assembly.GetAssembly(typeof(Jemgine.Particles.Distributor)));
        }

        public void SaveConfig()
        {
            String ConfigFilename = PrepareConfigFile();

            XmlWriterSettings Settings = new XmlWriterSettings();
            Settings.Indent = true;
            XmlWriter Writer = XmlWriter.Create(ConfigFilename, Settings);
            IntermediateSerializer.Serialize<Config>(Writer, _config, ConfigFilename);
            Writer.Close();
        }

        public Texture2D GetTexture(String name) { return Content.GetTexture(name); }

        public bool PrepareEpisodeContent()
        {
            if (String.IsNullOrEmpty(_config.EngineFolder) || String.IsNullOrEmpty(_config.Episode))
            {
                var ISettings = new InitialSettings(_config, "Set path to editor and episode");
                var DR = ISettings.ShowDialog();
                if (DR == System.Windows.Forms.DialogResult.Cancel) return false;
            }

            bool EpisodeIsLoaded = false;

            while (!EpisodeIsLoaded)
            {

                try
                {
                    Content = new Engine.EpisodeContentManager(Services, _config.EngineFolder, _config.Episode);
                    EpisodeIsLoaded = true;
                }
                catch (Jemgine.Engine.EpisodeException e)
                {

                        var ISettings = new InitialSettings(_config, e.Message);
                        if (ISettings.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return false;
                }
            }

            Content.FrontLoadTextures();

            Jemgine.Data.ResourceEditor.InvokeResourceBrowser += (A,B) =>
            {
                var ResourceBrowser = new ResourceDialog();
                ResourceBrowser.FillList(Content);
                ResourceBrowser.SelectedResource = B;
                ResourceBrowser.ShowDialog();
                return ResourceBrowser.SelectedResource;
            };


            return true;
        }

        private String _FileName;
        public String FileName { get { return _FileName; } }

        public bool FileSet { get; private set; }

        private void SetFile(String FileName)
        {
            _FileName = FileName;
        }

        public void OpenMap(String filename)
        {
            try
            {
                XmlReader Reader = XmlReader.Create(filename);
                Effect = IntermediateSerializer.Deserialize<Jemgine.Particles.ParticleEffect>(Reader, filename);
                Reader.Close();
            }
            catch (Exception e)
            {
                return;
            }

            SetFile(filename);
            FileSet = true;

            EffectLoaded();
            _hasUnsavedChanges = false;
        }

        
        public void SaveMap()
        {
            if (!FileSet) throw new InvalidOperationException();
            XmlWriterSettings Settings = new XmlWriterSettings();
            Settings.Indent = true;
            XmlWriter Writer = XmlWriter.Create(FileName, Settings);
            IntermediateSerializer.Serialize<Jemgine.Particles.ParticleEffect>(Writer, Effect, FileName);
            Writer.Close();

            _hasUnsavedChanges = false;
        }

        public void NewMap()
        {
            Effect = new Particles.ParticleEffect();
            SetFile("untitled.pfx");
            FileSet = false;

            EffectLoaded();

            _hasUnsavedChanges = false;
        }

        public void SaveMapAs(String filename)
        {
            SetFile(filename);
            FileSet = true;
            SaveMap();
        }

	}
}
